<?php

namespace app\model\oa;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 车辆管理模型
 * @package app\model\oa
 */
class Car extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'car';

    // 主键
    protected $pk = 'id';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'car_no' => 'string',
        'brand' => 'string',
        'model' => 'string',
        'color' => 'string',
        'engine_no' => 'string',
        'frame_no' => 'string',
        'buy_time' => 'datetime',
        'buy_price' => 'float',
        'current_price' => 'float',
        'insurance_time' => 'datetime',
        'inspection_time' => 'datetime',
        'status' => 'integer',
        'driver_id' => 'integer',
        'remark' => 'string',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];

    // 车辆状态常量
    const STATUS_NORMAL = 1;      // 正常
    const STATUS_MAINTENANCE = 2; // 维修中
    const STATUS_SCRAP = 3;       // 已报废
    const STATUS_RENT = 4;        // 外租

    /**
     * 获取状态文本
     */
    public static function getStatusText($status)
    {
        $texts = [
            self::STATUS_NORMAL => '正常',
            self::STATUS_MAINTENANCE => '维修中',
            self::STATUS_SCRAP => '已报废',
            self::STATUS_RENT => '外租',
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 关联驾驶员
     */
    public function driver()
    {
        return $this->belongsTo('app\model\admin\User', 'driver_id', 'id');
    }

    /**
     * 关联费用记录
     */
    public function fees()
    {
        return $this->hasMany('app\model\oa\CarFee', 'car_id', 'id');
    }

    /**
     * 关联里程记录
     */
    public function mileages()
    {
        return $this->hasMany('app\model\oa\CarMileage', 'car_id', 'id');
    }

    /**
     * 关联维修记录
     */
    public function repairs()
    {
        return $this->hasMany('app\model\oa\CarRepair', 'car_id', 'id');
    }

    /**
     * 获取车辆列表
     */
    public static function getList($params = [])
    {
        $query = self::with(['driver'])->order('create_time', 'desc');

        // 按状态筛选
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        // 按车牌号搜索
        if (!empty($params['car_no'])) {
            $query->where('car_no', 'like', '%' . $params['car_no'] . '%');
        }

        // 按品牌搜索
        if (!empty($params['brand'])) {
            $query->where('brand', 'like', '%' . $params['brand'] . '%');
        }

        // 按型号搜索
        if (!empty($params['model'])) {
            $query->where('model', 'like', '%' . $params['model'] . '%');
        }

        // 按驾驶员筛选
        if (!empty($params['driver_id'])) {
            $query->where('driver_id', $params['driver_id']);
        }

        return $query->paginate($params['limit'] ?? 15);
    }

    /**
     * 获取正常状态的车辆
     */
    public static function getNormalCars()
    {
        return self::where('status', self::STATUS_NORMAL)
            ->order('car_no', 'asc')
            ->select();
    }

    /**
     * 获取车辆统计
     */
    public static function getStatistics()
    {
        $total = self::count();
        $normal = self::where('status', self::STATUS_NORMAL)->count();
        $maintenance = self::where('status', self::STATUS_MAINTENANCE)->count();
        $scrap = self::where('status', self::STATUS_SCRAP)->count();
        $rent = self::where('status', self::STATUS_RENT)->count();

        return [
            'total' => $total,
            'normal' => $normal,
            'maintenance' => $maintenance,
            'scrap' => $scrap,
            'rent' => $rent,
        ];
    }

    /**
     * 检查保险是否到期
     */
    public function isInsuranceExpired()
    {
        return $this->insurance_time && strtotime($this->insurance_time) < time();
    }

    /**
     * 检查年检是否到期
     */
    public function isInspectionExpired()
    {
        return $this->inspection_time && strtotime($this->inspection_time) < time();
    }

    /**
     * 获取即将到期的保险
     */
    public static function getExpiringInsurance($days = 30)
    {
        $expiryDate = date('Y-m-d', strtotime("+$days days"));
        return self::where('insurance_time', '<=', $expiryDate)
            ->where('status', '<>', self::STATUS_SCRAP)
            ->order('insurance_time', 'asc')
            ->select();
    }

    /**
     * 获取即将到期的年检
     */
    public static function getExpiringInspection($days = 30)
    {
        $expiryDate = date('Y-m-d', strtotime("+$days days"));
        return self::where('inspection_time', '<=', $expiryDate)
            ->where('status', '<>', self::STATUS_SCRAP)
            ->order('inspection_time', 'asc')
            ->select();
    }

    /**
     * 搜索器 - 车牌号
     */
    public function searchCarNoAttr($query, $value)
    {
        $query->where('car_no', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 品牌
     */
    public function searchBrandAttr($query, $value)
    {
        $query->where('brand', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 型号
     */
    public function searchModelAttr($query, $value)
    {
        $query->where('model', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 状态
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    /**
     * 搜索器 - 驾驶员ID
     */
    public function searchDriverIdAttr($query, $value)
    {
        $query->where('driver_id', $value);
    }

    /**
     * 搜索器 - 购买时间范围
     */
    public function searchBuyTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('buy_time', $value);
        }
    }

    /**
     * 搜索器 - 保险时间范围
     */
    public function searchInsuranceTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('insurance_time', $value);
        }
    }

    /**
     * 搜索器 - 年检时间范围
     */
    public function searchInspectionTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('inspection_time', $value);
        }
    }
}